package org.osiris.server.servlets;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

public class SimplePictureFormUploader extends HttpServlet implements Servlet
{

  private static final long serialVersionUID = 8305367618713715640L;
  private static final String VALID_EXT = "jpg";
  Logger logger=Logger.getLogger(this.getClass());
  public static final String pinturesPath = System.getProperty("user.home")+File.separator+"afuptoolPictures";

  protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
    response.setContentType("text/plain");
    File maindir=new File(pinturesPath);
    if(!maindir.exists()){
    	logger.error("Error "+maindir.getAbsolutePath()+" no existe.");
    }
    
    FileItem uploadItem = getFileItem(request);
    if (uploadItem == null) {    	
      response.getWriter().write("NO-SCRIPT-DATA");
      return;
    }
    logger.info("uploadItem.getName():"+uploadItem.getName());
    logger.info("uploadItem.getFieldName():"+uploadItem.getFieldName());
    String seed = null;
	try {
	//	seed = com.rfef.fenix.afuptool.utils.PasswordGenerator.generate(32);
	} catch (Exception e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	logger.info("Seed generated:"+uploadItem.getName());
    String fn=maindir+File.separator+seed+"."+VALID_EXT;
    logger.info("File for write:"+fn);
    try {
		uploadItem.write(new File(fn));
	} catch (Exception e) {
		e.printStackTrace();
	}
	logger.info("writeed:"+fn);
	logger.info("seed:"+seed);
    response.getWriter().write("seed:"+seed+":seed");
    response.getWriter().flush();
    response.getWriter().close();           
  }

  @SuppressWarnings("unchecked")
private FileItem getFileItem(HttpServletRequest request) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
      List items = upload.parseRequest(request);
      logger.info("List is:"+items);
      Iterator it = items.iterator();
      while (it.hasNext()) {
    	  
        FileItem item = (FileItem) it.next();
        
        if (!item.isFormField() && "uploadFormElement".equals(item.getFieldName())) {
          return item;
        }
      }
    } catch (FileUploadException e) {
      return null;
    }
    return null;
  }

} 